<template>
  <view>
    <view class="city">
      <!-- #ifdef H5  -->
      <view class="city_close" @click="close_city">
        <uni-icons type="closeempty" size="20"></uni-icons>
      </view>
      <!-- #endif -->
      <view class="city_title">当前城市</view>
      <view class="city_title_row">
        <uni-icons type="left" size="30" @click="goBack()" style="margin-right: 20rpx;"></uni-icons>
        <view class="city_title_row_name">{{ mapVal.name || '城市' }}</view>
      </view>
      <!-- 添加输入框用于模糊查询 -->
      <view class="search-box">
        <input type="text" v-model="searchQuery" placeholder="请输入城市名" @input="handleSearch"/>
      </view>
    </view>
    <view v-if="!searchQuery" class="indexed">
      <uni-indexed-list :options="filteredCityList" :showSelect="false" @click="bindClick"></uni-indexed-list>
    </view>
    <view>
      <view v-for="(item,index) in filteredCityList" @click="selectCity(item)" :key="index">
        <view
            style="color: #191919;line-height: 100rpx;border-bottom: 2rpx solid #DEDEDE;width: 710rpx; margin: 0 auto;">
          {{ item.name }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {
  computed,
  ref
} from 'vue';
import sheep from '@/sheep';
import {
  onLoad,
} from '@dcloudio/uni-app';

const cityList = ref([])
const cityLists = ref([])
const mapVal = ref({
  name: '黄冈',
  id: ''
})
const searchQuery = ref('') // 添加搜索查询变量

onLoad(async (options) => {
  if (uni.getStorageSync('index-map')) {
    mapVal.value = uni.getStorageSync('index-map');
  }
  await getCityList();
})

// 获取城市数据
async function getCityList() {
  try {
    uni.showLoading({
      title: '加载中...'
    });

    // 使用正确的接口获取城市列表
    let result = await sheep.$api.noAuth.getCityList();

    // 确保数据格式正确
    if (result && result.code === 200 && Array.isArray(result.data.data)) {
      cityList.value = result.data.result;
      cityLists.value = result.data.data;
    } else {
      console.error('城市数据格式错误:', result);
    }
  } catch (error) {
    console.error('获取城市列表失败:', error);
    uni.showToast({
      title: '获取城市列表失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
}

// 选择城市函数
function selectCity(item) {
  if (item) {
    console.log('选择的城市:', item);
    // 存储选择的城市信息
    uni.setStorageSync('index-map', {
      id: item.code || item.id,
      name: item.name
    });
    // 返回上一页
    uni.navigateBack();
  }
}

// 关闭
function close_city() {
  uni.navigateBack();
}

function goBack() {
  uni.navigateBack({
    delta: 1
  })
}

// 手动选择城市
async function bindClick(e) {
  console.log('选择的城市:', e);
  if (e.item && e.item.name) {
    const selectedCity = {
      name: e.item.name,
      // 根据实际数据结构调整id/code字段
      id: e.item.code || e.item.id || await cityLists.value.find(item => item.name === e.item.name)?.id
    };

    console.log('确认选择的城市:', selectedCity);
    // 存储选择的城市信息
    uni.setStorageSync('index-map', selectedCity);
    // 返回上一页
    uni.navigateBack();
  }
}

// 模糊查询处理函数
function handleSearch() {
  filteredCityList.value = cityLists.value.filter(city => city.name.includes(searchQuery.value));
}

// 计算属性，用于过滤城市列表
const filteredCityList = computed(() => {
  if (searchQuery.value) {
    return cityLists.value.filter(city => city.name.includes(searchQuery.value));
  }
  return cityList.value;
});
</script>

<style scoped lang="scss">
.city {
  padding-top: 120rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  width: 690rpx;
  height: 180rpx;
  margin: 0 auto;

  &_close {
    position: absolute;
    right: 0;
    top: 10rpx;
    padding: 10rpx 20rpx;
  }

  &_title {
    font-weight: 600;

    &_row {
      display: flex;
      align-items: center;

      &_name {
        padding: 6rpx 33rpx;
        text-align: center;
        border-radius: 40rpx;
      }

      &_btn {
        padding: 6rpx 33rpx;
        text-align: center;
        border-radius: 40rpx;
        margin-left: 33rpx;
      }
    }
  }
}

// 添加搜索框样式
.search-box {
  margin: 20rpx;

  input {
    width: 100%;
    padding: 10rpx;
    border: 1rpx solid #ccc;
    border-radius: 10rpx;
    height: 30rpx;
  }
}

::v-deep .uni-indexed-list {
  height: calc(100vh - 200rpx); // 调整高度以适应搜索框
  overflow: hidden;
  position: unset !important;
}
</style>
